srvMap.add('queryAllScopeTree','','front/sh/link!execute?uid=queryAllScopeTree');
srvMap.add('scopeQueryAreaByUser','','front/sh/link!execute?uid=scopeQueryAreaByUser');
srvMap.add('scopeQueryUserByArea','','front/sh/link!execute?uid=scopeQueryUserByArea');
srvMap.add('scopeModify','','front/sh/link!execute?uid=scopeModify');
srvMap.add('scopeDelete','','front/sh/link!execute?uid=scopeDelete');

var ztree_user, ztree_area;

$(function() {
	$(".form-submit-add").on("click", addSave);
	$(".form-submit-delete").on("click", deleteSave);
	$("#userSearchBtn").on("click", userSearch);
	$("#areaSearchBtn").on("click", areaSearch);
	$(document).delegate('#userSearchInput', 'keyup', function(event) {
		var keycode = event.keyCode;
		if (keycode == 13) {
			userSearch();
		}
	});
	
	$(document).delegate('#areaSearchInput', 'keyup', function(event) {
		var keycode = event.keyCode;
		if (keycode == 13) {
			areaSearch();
		}
	});
	// 查看模式事件
	bindViewMode();

	// 初始化ztree高度
	initZtreeBox();

	$(window).resize(function(event) {
		// 初始化ztree高度
		initZtreeBox();
	});
	//查询所有树的数据
	initAllTree();

});

/**
 * 初始化ztree高度
 * @return {[type]} [description]
 */
function initZtreeBox() {
	var h = $(window).height(),
		bh = $(".form-submit-box").outerHeight(),
		t = $(".ztree").offset().top;
	h = h - bh - t - 31;
	$(".ztree").height(h);
}

function initAllTree(){
	var par = "";
	Util.ajax.postJsonSync(srvMap.get('queryAllScopeTree'),par,function(json,status){
		if(status){
			if (null == json.object ) {
				return;
			}
			if (null != json.object.user) {
				initUser(json.object.user);
			}
			if (null != json.object.area ) {
				initArea(json.object.area);
			}
			
			// 隐藏进度条
			$(".loadingSmall").css({
				'background-position': '-1000px -1000px'
			});
		}
		else{
			 alert('初始化列表出错！');
		}
	});
	
	
//	var url = CONTENT_PATH + "/com.asiainfo.manage.LinkAction.queryAllScopeTree.invoke";
//	Base.ajax({
//		url: url,
//		success: function(req) {
//			if (null == req ) {
//				return;
//			}
//			if (null != req.user) {
//				initUser(req.user);
//			}
//			if (null != req.area ) {
//				initArea(req.area);
//			}
//			
//			// 隐藏进度条
//			$(".loadingSmall").css({
//				'background-position': '-1000px -1000px'
//			});
//		}
//	});
}
/**
 * 初始化用户
 * @return {[type]} [description]
 */
function initUser(data) {
			var zNodes = data;
			for (var i = zNodes.length - 1; i >= 0; i--) {
					var z = zNodes[i];
					if(z.type == "user"){
						z.name = '<i class="iconfont icon-yonghu"></i> ' + z.name;
					}
					z.name = z.name + " ["+z.id+"]";
					zNodes[i] = z;
				};
			var setting = {
				view: {
					showIcon: false,
					nameIsHTML: true,
					showTitle: false,
					fontCss: function(treeId, treeNode) {
						var o = {};
						if (treeNode.type == "user") {
							o = {
								"color": "#32b5cb",
								"font-weight": "bold"
							};
						}

						o = treeNode.highlight ? {
							color: "red",
							"font-weight": "bold"
						} : {
							color: "#32b5cb",
							"font-weight": "bold"
						};
						return o;
					}
				},
				check: {
					enable: true,
					chkboxType: {
						"Y": "s",
						"N": "ps"
					}
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onCheck: queryAreaByUser,
					beforeClick: function(event, treeId, treeNode) {
						return false;
					}
				}
			};


			ztree_user = $.fn.zTree.init($("#userTree"), setting, zNodes);
			if(userQId !=''){
				userCheckedById(userQId);
			}
			dealFolderWithoutChildren(ztree_user);
			ztree_user.expandAll(true);
}

/**
 * 初始化地域
 * @return {[type]} [description]
 */
function initArea(data) {
			var zNodes = [];
			for (var i = 0; i < data.length; i++) {
				if (data[i].id.length<=3) {
					zNodes.push(data[i]);
				}
			}
			var setting = {
				view: {
					showIcon: false,
					nameIsHTML: true,
					fontCss: function(treeId, treeNode) {
						return treeNode.highlight ? {
							color: "red",
							"font-weight": "bold"
						} : {
							color: "#e89531",
							"font-weight": "bold"
						};
					}
				},
				check: {
					enable: true,
					chkboxType: {
						"Y": "",
						"N": ""
					}
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onCheck: queryUserByArea,
					beforeClick: function(event, treeId, treeNode) {
						return false;
					}
				}
			};

			ztree_area = $.fn.zTree.init($("#areaTree"), setting, zNodes);
			ztree_area.expandAll(true);
}

/**
 * 
 * @Description : 数据权限新增-保存
 * @return void
 * 
 * @author : wucm
 * @date : 2015年8月3日 下午7:42:25
 * 
 */
function addSave() {
	//查看模式不能保存
	if ($("#viewMode").prop("checked")) {
		return;
	}

	//判空
	var user_nodes = ztree_user.getCheckedNodes(true);
	var area_nodes = ztree_area.getCheckedNodes(true);
	if (user_nodes.length == 0 || area_nodes.length == 0) {
		return;
	}

	//拼接参数
	var uId = [],
		uName = [],
		aId = [],
		aName = [];
	for (var i = user_nodes.length - 1; i >= 0; i--) {
		var u = user_nodes[i];
		if (u.type == "user") {
			uId.push(u.id);
			uName.push(u.name);
		}
	};
	for (var i = area_nodes.length - 1; i >= 0; i--) {
		var a = area_nodes[i];
		aId.push(a.id);
		aName.push(a.name);
	};
	uId = uId.join(";");
	uName = uName.join(";");
	aId = aId.join(";");
	aName = aName.join(";");

	var data = {
		"users": uId,
		"areas": aId
	};

	var d = top.dialog({
		title: '保存确认',
		content: '确认保存以下对数据应权限：<br/>' + uName + "<----->" + aName+"？",
		width:'350px',
		okValue: '确定',
		ok: function() {
			this.title('提交中…');

			// 保存提交
			addSaveSubmit(data);

			return true;
		},
		cancelValue: '取消',
		cancel: function() {}
	});
	d.showModal();
}

/**
 * 数据权限新增-保存
 * @return {[type]} [description]
 */
function addSaveSubmit(data) {
	var par = "&users="+data.users+"&areas="+data.areas;
	Util.ajax.postJsonSync(srvMap.get('scopeModify'),par,function(json,status){
		if(status){
			if (null == json.object || null == json.object.result) {
				return;
			}

			if (json.object.result) {
				$M.successTip("保存成功");
			} else {
				$M.failureTip("保存失败");
			}
			setTimeout(function() {
				$(".form-tip").html("");
			}, 5000);
		}
	});
	
//	var url = CONTENT_PATH + "/com.asiainfo.manage.LinkAction.scopeModify.invoke";
//	Base.ajax({
//		url: url,
//		data: data,
//		success: function(req) {
//			if (null == req || null == req.result) {
//				return;
//			}
//
//			if (req.result) {
//				$M.successTip("保存成功");
//			} else {
//				$M.failureTip("保存失败");
//			}
//			setTimeout(function() {
//				$(".form-tip").html("");
//			}, 5000);
//		}
//	});
}


/**
 * 
 * @Description : 数据权限删除-保存
 * @return void
 * 
 * @author : wucm
 * @date : 2015年8月3日 下午7:42:25
 * 
 */
function deleteSave() {
	//查看模式不能保存
	if ($("#viewMode").prop("checked")) {
		return;
	}

	//判空
	var user_nodes = ztree_user.getCheckedNodes(true);
	var area_nodes = ztree_area.getCheckedNodes(true);
	if (user_nodes.length == 0 || area_nodes.length == 0) {
		return;
	}

	//拼接参数
	var uId = [],
		uName = [],
		aId = [],
		aName = [];
	for (var i = user_nodes.length - 1; i >= 0; i--) {
		var u = user_nodes[i];
		if (u.type == "user") {
			uId.push(u.id);
			uName.push(u.name);
		}
	};
	for (var i = area_nodes.length - 1; i >= 0; i--) {
		var a = area_nodes[i];
		aId.push(a.id);
		aName.push(a.name);
	};
	uId = uId.join(";");
	uName = uName.join(";");
	aId = aId.join(";");
	aName = aName.join(";");

	var data = {
		"users": uId,
		"areas": aId
	};

	var d = top.dialog({
		title: '保存确认',
		content: '确认删除以下对应数据权限：<br/>' + uName + "<----->" + aName+"？",
		width:'350px',
		okValue: '确定',
		ok: function() {
			this.title('提交中…');

			// 保存提交
			deleteSaveSubmit(data);

			return true;
		},
		cancelValue: '取消',
		cancel: function() {}
	});
	d.showModal();
}

/**
 * 数据权限删除-保存提交
 * @return {[type]} [description]
 */
function deleteSaveSubmit(data) {
	var par = "&users="+data.users+"&areas="+data.areas;
	Util.ajax.postJsonSync(srvMap.get('scopeDelete'),par,function(json,status){
		if(status){
			if (null == json.object || null == json.object.result) {
				return;
			}

			if (json.object.result) {
				$M.successTip("删除成功");
				clearAllLight();
			} else {
				$M.failureTip("删除失败");
			}
			setTimeout(function() {
				$(".form-tip").html("");
			}, 5000);
		}
	});
	
	
	
//	var url = CONTENT_PATH + "/com.asiainfo.manage.LinkAction.scopeDelete.invoke";
//	Base.ajax({
//		url: url,
//		data: data,
//		success: function(req) {
//			if (null == req || null == req.result) {
//				return;
//			}
//
//			if (req.result) {
//				$M.successTip("删除成功");
//				clearAllLight();
//			} else {
//				$M.failureTip("删除失败");
//			}
//			setTimeout(function() {
//				$(".form-tip").html("");
//			}, 5000);
//		}
//	});
}

/**
 * 查看模式事件
 * @return {[type]} [description]
 */
function bindViewMode() {
	var _o = $("#viewMode");
	_o.change(function(event) {
		var flag = _o.prop("checked");
		var _os = $(".form-submit");
		clearAllLight();
		if (flag) {
			_os.prop("disabled", true);
			$(".form-tip").val('');
			ztree_user.checkAllNodes(false);
			ztree_area.checkAllNodes(false);
		} else {
			_os.prop("disabled", false);
		}
	});
}

/**
 * 用户搜索
 * @return {[type]} [description]
 */
function userSearch() {
	var s = $("#userSearchInput").val();
	s = $.trim(s);

	var nodes = ztree_user.getNodes();
	nodes = ztree_user.transformToArray(nodes);

	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
		var id = node.id;
		var name = node.name;
		var type = node.type;

		// 先显示节点，再进行搜索匹配
		ztree_user.showNode(node);

		if (s.length > 0 && (id.indexOf(s) != -1 || name.indexOf(s) != -1) && "user" == type) {
			node.highlight = true;
			ztree_user.updateNode(node);
		}else if(s.length > 0 && "user" == type){
			node.highlight = false;
 			ztree_user.hideNode(node);
			ztree_user.updateNode(node);
		}else if("user" == type){   //没有匹配字串的时候都常规显示
			node.highlight = false;
			ztree_user.showNode(node);
 			ztree_user.updateNode(node);
		}
	};
}

/**
 * 地域搜索
 * @return {[type]} [description]
 */
function areaSearch() {
	var s = $("#areaSearchInput").val();
	s = $.trim(s);

	var nodes = ztree_area.getNodes();
	nodes = ztree_area.transformToArray(nodes);

	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
		var id = node.id;
		var name = node.name;
		var isParent=node.isParent;

		// 先显示节点，再进行搜索匹配
		ztree_area.showNode(node);

		if (s.length > 0 && (id.indexOf(s) != -1 || name.indexOf(s) != -1)) {
			node.highlight = true;
			ztree_area.updateNode(node);
		}else if(s.length > 0 && !isParent){
			node.highlight = false;
			ztree_area.hideNode(node);
			ztree_area.updateNode(node);
		}else{
			node.highlight = false;
			ztree_area.showNode(node);
 			ztree_area.updateNode(node);
		}
	};
}

/**
 * 根据用户查询地域
 * @return {[type]} [description]
 */
function queryAreaByUser(event, treeId, treeNode) {
	//先清空ztree_area状态
	ztree_area.checkAllNodes(false);
	var hNodes = ztree_area.getNodes();
	hNodes = ztree_area.transformToArray(hNodes);
	for (var i = hNodes.length - 1; i >= 0; i--) {
		var node = hNodes[i];
		node.highlight = false;
		ztree_area.updateNode(node);
	};

	//如果是查看模式，则只能单选
	if ($("#viewMode").prop("checked")) {
		var nodes = ztree_user.getNodes();
		nodes = ztree_user.transformToArray(nodes);
		for (var i = nodes.length - 1; i >= 0; i--) {
			var node = nodes[i];
			if (node.tId != treeNode.tId) {
				ztree_user.checkNode(node, false, false);
				node.highlight = false;
				ztree_user.updateNode(node);
			}
		};
		
		if(treeNode.checked){
			treeNode.highlight = true;
			ztree_user.updateNode(treeNode);
		}else{
			treeNode.highlight = false;
			ztree_user.updateNode(treeNode);
		}
	}else {
		return;
	}

	var user_nodes = ztree_user.getCheckedNodes(true);
	if (user_nodes.length != 1) {
		return;
	}

	//参数
	var node = user_nodes[0];
	var userId = node.id;
	var data = {
		userId: userId
	};

	var par = "&selUserId="+userId;
	Util.ajax.postJsonSync(srvMap.get('scopeQueryAreaByUser'),par,function(json,status){
		if(status){

			if (null == json.object || null == json.object.result) {
				return;
			}

			//添加ztree_area状态
			var data = json.object.result;
			for (var i = data.length - 1; i >= 0; i--) {
				var aId = data[i];
				var node = ztree_area.getNodeByParam("id", aId, null);
				if (null == node) {
					continue;
				}
				node.highlight = true;
				ztree_area.checkNode(node, true, true);
				ztree_area.updateNode(node);
			};
		}
		else{
			 alert('根据用户查询地域出错！');
		}
	});
	
//	var url = CONTENT_PATH + "/com.asiainfo.manage.LinkAction.scopeQueryAreaByUser.invoke";
//	Base.ajax({
//		url: url,
//		data: data,
//		success: function(req) {
//			if (null == req || null == req.result) {
//				return;
//			}
//
//			//添加ztree_area状态
//			var data = req.result;
//			for (var i = data.length - 1; i >= 0; i--) {
//				var aId = data[i];
//				var node = ztree_area.getNodeByParam("id", aId, null);
//				if (null == node) {
//					continue;
//				}
//				node.highlight = true;
//				ztree_area.checkNode(node, true, true);
//				ztree_area.updateNode(node);
//			};
//		}
//	});
}

/**
 * 根据地域查询用户
 * @return {[type]} [description]
 */
function queryUserByArea(event, treeId, treeNode) {
	//如果是查看模式，则只能单选
	if ($("#viewMode").prop("checked")) {
		var nodes = ztree_area.getNodes();
		nodes = ztree_area.transformToArray(nodes);
		for (var i = nodes.length - 1; i >= 0; i--) {
			var node = nodes[i];
			if (node.tId != treeNode.tId) {
				ztree_area.checkNode(node, false, false);
				if(node.highlight){
					node.highlight = false;
					ztree_area.updateNode(node);
				}
			}
		};
		if(treeNode.checked){
			treeNode.highlight = true;
			ztree_area.updateNode(treeNode);
		}else{
			treeNode.highlight = false;
			ztree_area.updateNode(treeNode);
		}
	} else {
		return;
	}

	//先清空ztree_area状态
	ztree_user.checkAllNodes(false);
	var hNodes = ztree_user.getNodes();
	hNodes = ztree_user.transformToArray(hNodes);
	for (var i = hNodes.length - 1; i >= 0; i--) {
		var node = hNodes[i];
		node.highlight = false;
		ztree_user.updateNode(node);
	};

	var user_nodes = ztree_area.getCheckedNodes(true);
	if (user_nodes.length != 1) {
		return;
	}

	//参数
	var node = user_nodes[0];
	var areaId = node.id;
	var data = {
		areaId: areaId
	};

	var par = "&selAreaId="+areaId;
	Util.ajax.postJsonSync(srvMap.get('scopeQueryUserByArea'),par,function(json,status){
		if(status){
			if (null == json.object || null == json.object.result) {
				return;
			}

			//添加ztree_area状态
			var data = json.object.result;
			for (var i = data.length - 1; i >= 0; i--) {
				var uId = data[i];
				var node = ztree_user.getNodeByParam("id", uId, null);
				if (null == node) {
					continue;
				}
				node.highlight = true;
				ztree_user.checkNode(node, true, true);
				ztree_user.updateNode(node);
			};
		}
		else{
			 alert('根据地域查询用户出错！');
		}
	});
	
//	var url = CONTENT_PATH + "/com.asiainfo.manage.LinkAction.scopeQueryUserByArea.invoke";
//	Base.ajax({
//		url: url,
//		data: data,
//		success: function(req) {
//			if (null == req || null == req.result) {
//				return;
//			}
//
//			//添加ztree_area状态
//			var data = req.result;
//			for (var i = data.length - 1; i >= 0; i--) {
//				var uId = data[i];
//				var node = ztree_user.getNodeByParam("id", uId, null);
//				if (null == node) {
//					continue;
//				}
//				node.highlight = true;
//				ztree_user.checkNode(node, true, true);
//				ztree_user.updateNode(node);
//			};
//		}
//	});
}


/**
 * 
* @Description :去掉红色高亮显示
* @author  xueyf3 
* @date 创建时间：2015年8月29日 下午9:24:10 
* @version 1.0
 */
function clearAllLight(){
	var nodes = ztree_user.getCheckedNodes(true);
	nodes = ztree_user.transformToArray(nodes);
	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
			node.highlight = false;
			ztree_user.checkNode(node, false, false);
			ztree_user.updateNode(node);
	};
	
	nodes = ztree_area.getCheckedNodes(true);
	nodes = ztree_area.transformToArray(nodes);
	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
			node.highlight = false;
			ztree_area.checkNode(node, false, false);
			ztree_area.updateNode(node);
	};
}

/**
	*去掉树上的空节点
	*
	**/
function dealFolderWithoutChildren(treeObj){
	var nodes = treeObj.getNodes();
	nodes = treeObj.transformToArray(nodes);
	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
		var isParent = node.isParent;
		if(isParent && !node.children){
				treeObj.removeNode(node);
		}
	};
}

/**
 * 根据需要赋权的用户编码，初始化用户树
 * @return {[type]} [description]
 */
function  userCheckedById(userId){
	var nodes = ztree_user.getNodes();
	nodes = ztree_user.transformToArray(nodes);
	for (var i = nodes.length - 1; i >= 0; i--) {
		var node = nodes[i];
		var id = node.id;
		var name = node.name;
		var type = node.type;
		if (id == userId && "user" == type) {
			node.checked = true;
			ztree_user.updateNode(node);
		}else if("user" == type){
 			ztree_user.removeNode(node);
		}
	};
}